﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Uco.Models;
using System.Diagnostics;
using System.Net.Mail;
using System.Configuration;
using System.Text;
using System.Reflection;
using System.Globalization;
using System.Web.Configuration;
using System.Dynamic;
using System.Web.Mvc;
using System.Xml;
using System.Text.RegularExpressions;

namespace Uco.Infrastructure
{
    public static partial class SF
    {
        #region Errors

		public static void LogHttpError(HttpException httpEx)
        {
            if (httpEx.GetHttpCode() != 404) LogError((Exception)httpEx);
        }
		
        public static void LogError(string Ex)
        {
            LogError(new Exception(Ex));
        }

        public static void LogError(Exception Ex)
        {
            if (ConfigurationManager.AppSettings["LogToEmail"] == "true")
            {
                MailMessage mm = new MailMessage(ConfigurationManager.AppSettings["MailFrom"], ConfigurationManager.AppSettings["LogToEmailName"]);
                mm.Subject =
                    (HttpContext.Current.Request.ServerVariables["HTTP_HOST"] != null ? HttpContext.Current.Request.ServerVariables["HTTP_HOST"] : "")
                    + " - "
                    + (Ex.Message != null ? Ex.Message : "");
                mm.Body = mm.Body + (Ex.InnerException != null ? Ex.InnerException.ToString() : "") + "<br />";
                mm.Body = mm.Body + (Ex.Message != null ? Ex.Message : "") + "<br />";
                mm.Body = mm.Body + (Ex.Source != null ? Ex.Source : "") + "<br />";
                mm.Body = mm.Body + (Ex.StackTrace != null ? Ex.StackTrace : "") + "<br />";
                mm.Body = mm.Body + (Ex.TargetSite != null ? Ex.TargetSite.ToString() : "") + "<br />";
                mm.Body = mm.Body + (HttpContext.Current.User.Identity.IsAuthenticated == true ? HttpContext.Current.User.Identity.Name : "") + "<br />";
                mm.Body = mm.Body + (HttpContext.Current.Request.PhysicalPath != null ? HttpContext.Current.Request.PhysicalPath : "") + "<br />";
                mm.Body = mm.Body + (HttpContext.Current.Request.UserAgent != null ? HttpContext.Current.Request.UserAgent : "") + "<br />";
                mm.Body = mm.Body + (HttpContext.Current.Request.UserHostAddress != null ? HttpContext.Current.Request.UserHostAddress : "") + "<br />";
                mm.Body = mm.Body + (HttpContext.Current.Request.Url != null ? HttpContext.Current.Request.Url.AbsoluteUri : "") + "<br />";
                mm.Body = mm.Body + (HttpContext.Current.Request.UrlReferrer != null ? HttpContext.Current.Request.UrlReferrer.AbsoluteUri : "") + "<br />";
                mm.BodyEncoding = Encoding.UTF8;
                mm.SubjectEncoding = Encoding.UTF8;
                mm.IsBodyHtml = true;
                SmtpClient client = new SmtpClient();
                client.Send(mm);
            }

        }

        #endregion

        #region Get/Set single from Db

        public static string GetTextComponent(string SystemName)
        {
            TextComponent tc = SF.GetTextComponentsRepository().FirstOrDefault(r => r.SystemName == SystemName);
            if (tc != null) return tc.Text;
            else return string.Empty;
        }

        public static AbstractPage GetPageByUrl(string Url)
        {
            string[] UrlSplited = Url.Split('/');
            int UrlSplitedLength = UrlSplited.Length;
            if (UrlSplitedLength < 2) return null;
            string SeoUrlName = UrlSplited[UrlSplitedLength - 1].ToLower();
            string RouteUrl = UrlSplited[UrlSplitedLength - 2].ToLower();

            return SF.LoadPage(SeoUrlName);
        }

        #endregion

        #region Attributes

        public static string GetTypeRouteUrl(Type t)
        {
            object[] attributes = t.GetCustomAttributes(typeof(RouteUrlAttribute), false);
            foreach (object item in attributes)
            {
                RouteUrlAttribute at = (RouteUrlAttribute)item;
                return at.RouteUrl;
            }
            return string.Empty;
        }

        public static List<string> GetTypeRestrictParentsAttribute(Type t)
        {
            object[] attributes = t.GetCustomAttributes(typeof(RestrictParentsAttribute), false);
            foreach (object item in attributes)
            {
                RestrictParentsAttribute at = (RestrictParentsAttribute)item;
                return at.Parents.ToList();
            }
            return new List<string>();
        }

        #endregion

        #region Reflection
        
        public static List<Type> GetAbstractPageChildClasses()
        {
            List<Type> childClasses = new List<Type>();
            AppDomain currentDomain = AppDomain.CurrentDomain;
            Assembly[] assems = currentDomain.GetAssemblies();
            foreach (Assembly assem in assems)
            {
                if (assem.FullName.StartsWith("Uco"))
                {
                    Type[] ts = assem.GetTypes();
                    foreach (Type t in ts)
                    {
                        if (t.IsSubclassOf(typeof(AbstractPage))) childClasses.Add(t);
                    }
                }
            }
            return childClasses;
        }

        #endregion

        #region General

        public static string GetImageUrl(string Pic, int Width, int Height, bool ExactSize, bool ToCacheFile)
        {
            return "~/Image?img=" + HttpUtility.UrlEncode(Pic) + "&w=" + Width + "&h=" + Height + "&t=" + (ExactSize ? "1" : "0") + "&c=" + (ToCacheFile ? "1" : "0");
        }

        public static string CleanUrl(string UrlToClean)
        {
            if (UrlToClean == null) return "";
            UrlToClean = UrlToClean.Trim();
            UrlToClean = UrlToClean.Replace(" ", "_");
            UrlToClean = UrlToClean.Replace(".", "_");
            UrlToClean = UrlToClean.Replace(",", "_");
            UrlToClean = UrlToClean.Replace("\"", "_");
            UrlToClean = UrlToClean.Replace("'", "_");
            UrlToClean = UrlToClean.Replace(",", "_");
            UrlToClean = UrlToClean.Replace("/", "_");
            UrlToClean = UrlToClean.Replace("\\", "_");
            UrlToClean = UrlToClean.Replace("!", "_");
            UrlToClean = UrlToClean.Replace("@", "_");
            UrlToClean = UrlToClean.Replace("#", "_");
            UrlToClean = UrlToClean.Replace("%", "_");
            UrlToClean = UrlToClean.Replace("^", "_");
            UrlToClean = UrlToClean.Replace("&", "_");
            UrlToClean = UrlToClean.Replace("*", "_");
            UrlToClean = UrlToClean.Replace("(", "_");
            UrlToClean = UrlToClean.Replace(")", "_");
            UrlToClean = UrlToClean.Replace("-", "_");
            UrlToClean = UrlToClean.Replace("+", "_");
            UrlToClean = UrlToClean.Replace("=", "_");
            UrlToClean = UrlToClean.Replace("?", "_");
            UrlToClean = UrlToClean.Replace("<", "_");
            UrlToClean = UrlToClean.Replace(">", "_");
            UrlToClean = UrlToClean.Replace("₪", "_");
            UrlToClean = UrlToClean.Replace("|", "_");

            UrlToClean = UrlToClean.Replace("_____", "_");
            UrlToClean = UrlToClean.Replace("____", "_");
            UrlToClean = UrlToClean.Replace("___", "_");
            UrlToClean = UrlToClean.Replace("__", "_");

            return UrlToClean;
        }

        public static string GetLangCode()
        {
            return System.Threading.Thread.CurrentThread.CurrentCulture.Name;
        }

        public static int RandomNumber(int min, int max)
        {
            Random random = new Random();
            return random.Next(min, max);
        }

        public static List<int> GetListIntFromString(string Text)
        {
            if (string.IsNullOrEmpty(Text)) return new List<int>();
            List<int> l = new List<int>();
            foreach (string item in Text.Split(','))
            {
                int tempInt = 0;
                int.TryParse(item.Trim(), out tempInt);
                l.Add(tempInt);
            }
            return l.Distinct().ToList();
        }

        public static bool isEmail(string inputEmail)
        {
            inputEmail = inputEmail ?? string.Empty;
            string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                  @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                  @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
            Regex re = new Regex(strRegex);
            if (re.IsMatch(inputEmail))
                return (true);
            else
                return (false);
        }

        public static void SetCookie(string CookieName, string CookieValue)
        {
            //Create a new cookie, passing the name into the constructor
            System.Web.HttpCookie cookie = new System.Web.HttpCookie(CookieName);
            //Set the cookies value
            cookie.Value = CookieValue;
            //Set the cookie to expire in 1 day
            DateTime dtNow = DateTime.Now;
            TimeSpan tsMinute = new TimeSpan(1, 0, 0, 0);
            cookie.Expires = dtNow + tsMinute;
            //Add the cookie
            System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
        }

        public static string GetCookie(string CookieValue)
        {
            //Grab the cookie
            System.Web.HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies[CookieValue];
            //Check to make sure the cookie exists
            if (cookie == null) return string.Empty;
            else
            {
                if (cookie.Value == null) return string.Empty;
                else return cookie.Value;
            }
        }

        #endregion
    }
}